package com.uduemc.biso.node.web.service.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.common.extities.ctemplatelistdata.CTemplateItemData;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.core.utils.ResultUtil;
import com.uduemc.biso.node.core.backend.feign.WebBackendFeign;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.service.byfeign.TemplateService;

@Service
public class TemplateServiceImpl implements TemplateService {

	@Autowired
	private WebBackendFeign webBackendFeign;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private GlobalProperties globalProperties;

	@Override
	public CTemplateItemData getCTemplateItemData(long templateId) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = webBackendFeign.getTemplateById(templateId);
		CTemplateItemData data = ResultUtil.data(restResult, CTemplateItemData.class);
		return data;
	}

	@Override
	public CTemplateItemData getCTemplateItemDataByUrl(String domain) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		RestResult restResult = webBackendFeign.getTemplateByUrl(domain);
		CTemplateItemData data = ResultUtil.data(restResult, CTemplateItemData.class);
		return data;
	}

	@Override
	public CTemplateItemData getCTemplateItemDataByUrl(HDomain hDomain) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (hDomain == null) {
			return null;
		}
		Short domainType = hDomain.getDomainType();
		if (domainType != null && domainType.shortValue() == (short) 0) {
			String domainName = hDomain.getDomainName();

			String cacheDataKey = globalProperties.getSiteRedisKey().getTemplateDomainCachekey(domainName);
			CTemplateItemData data = (CTemplateItemData) redisUtil.get(cacheDataKey);
			if (data == null) {
				String cacheNullDataKey= globalProperties.getSiteRedisKey().getNullTemplateDomainCachekey(domainName);
				Integer data1 = (Integer) redisUtil.get(cacheNullDataKey);
				if(data1 != null && data1.intValue() == 1) {
					return null;
				}
				
				data = getCTemplateItemDataByUrl(domainName);
				if (data != null) {
					redisUtil.set(cacheDataKey, data, 3600 * 24);
				}else {
					redisUtil.set(cacheNullDataKey, 1, 3600 * 24);
					return null;
				}
			}
			return data;
		}
		return null;
	}

}
